<template>
	<scroll-view scroll-y class="container" :style="{height: 'calc(100vh - ' + containerOutsideHeight + 'px)'}">
		<view class="fill-report">
			<view class="form">
				<view @click="jumpPageByType(1)" class="form-item">
					<view class="label required">项目名称</view>
					<view class="form-content">
						<view class="form-text">{{fillForm.project ? fillForm.project.name : ""}}</view>
						<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>
				
				<view @click="jumpPageByType(2)" class="form-item">
					<view class="label required">区间/站点</view>
					<view class="form-content">
						<view class="form-text">{{fillForm.intervalSite.length ? fillForm.intervalSite.map(item => item.name).join(",") : ""}}</view>
						<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>
				
				<view @click="jumpPageByType(3)" class="form-item">
					<view class="label required">安全监管人员</view>
					<view class="form-content">
						<view class="form-text">{{fillForm.supervisor ? fillForm.supervisor.map(item => item.name).join("、") : ""}}</view>
						<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>
				
				<view class="no-inline form-item" style="border-bottom: none;">
					<view class="label required">旁站照片</view>
					<u-upload @afterRead="event => addFile(event, 'sideStationFiles')" @delete="event => deleteFile(event, 'sideStationFiles')" :fileList="fillForm.sideStationFiles" multiple :maxCount="9"></u-upload>
				</view>
				
				<view class="form-item">
					<view class="label required" style="width: 260rpx;">劳务人员</view>
					<view class="form-content">
						<u--input inputAlign="right" v-model="fillForm.laborServiceNum" type="number" placeholder="请输入数量"  border="none" />
					</view>
				</view>
			</view>
			<view style="height: 40rpx;background-color: #f5f7fa;"></view>
			<view class="form">
				<view class="no-inline form-item" style="border-bottom: none;">
					<view class="label required">每日班前交底（签字文件）</view>
					<u-upload @afterRead="event => addFile(event, 'signFiles')" @delete="event => deleteFile(event, 'signFiles')" :fileList="fillForm.signFiles" multiple :maxCount="9"></u-upload>
				</view>
				
				<view class="no-inline form-item">
					<view class="label required">每日班前交底（现场照片）</view>
					<u-upload @afterRead="event => addFile(event, 'spotFiles')" @delete="event => deleteFile(event, 'spotFiles')" :fileList="fillForm.spotFiles" multiple :maxCount="9"></u-upload>
				</view>
			</view>
			<view style="height: 40rpx;background-color: #f5f7fa;"></view>
			<view class="form">
				<view @click="jumpPageByType(4)" class="form-item">
					<view class="label required">特殊工种人员</view>
					<view class="form-content"> 
						<view class="form-text">{{fillForm.workPersonnel.length ? fillForm.workPersonnel.map(item => item.name).join("、") : "无"}}</view>
						<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>
				
				<view class="form-item">
					<view class="label required">作业许可</view>
					<view class="form-content">
						<u-switch v-model="fillForm.isWorkAllow" @change="addOneDataWorkAllow" />
						<text>{{fillForm.isWorkAllow ? "有" : "无"}}</text>
					</view>
				</view>
			</view>
					
			<view v-if="fillForm.isWorkAllow" style="padding-bottom: 40upx; background: #fff;">
				<view v-for="(item, index) in fillForm.workAllowList" :key="index">
					<view style="font-weight: bold; line-height: 40upx; padding: 30upx 32upx 22upx; font-size: 28upx; background: #f5f7fa; display: flex; align-items: center; justify-content: space-between;">
						<view style="color: #445469;">作业许可{{index + 1}}</view>
						<view @click="removeWorkAllowList(index)" style="color: #ff6a6a;">删除</view>
					</view>
					
					<view style="padding: 14upx 32upx 0; color: #586981; font-size: 32upx;">
						<view style="font-weight: 500; height: 100upx; padding: 0 30upx 0 44upx; display: flex; align-items: center; justify-content: space-between; margin-bottom: 20upx;">
							<view>作业许可证名称</view>
							<picker @change="event => selectWorkAllowName(event, index)" :range="dictMap['work_permit_name']" range-key="name">
								<view style="display: flex; align-items: center;">
									<view style="margin-right: 36upx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 300upx;">
										{{item.index !== null ? dictMap['work_permit_name'][item.index].name : ""}}
									</view>
									<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
								</view>
							</picker>
						</view>
						
						<u-upload @afterRead="event => addFile(event, 'workAllowList', index)" @delete="event => deleteFile(event, 'workAllowList', 'fileArray', index)" :fileList="item.fileArray" multiple :maxCount="9"></u-upload>
					</view>
				</view>
				
				<view style="padding-top: 40upx;">
					<view @click="addWorkAllowList" style="display: flex; align-items: center; justify-content: center; height: 96upx; background: #f5f7fa; border-radius: 4upx; margin: 0 32upx;">
						<image src="/static/image/icon-add-fill.png" mode="aspectFill" style="width: 34upx; height: 34upx; margin-right: 18upx;"></image>
						<view style="color: #445469; font-weight: bold;">添加作业许可</view>
					</view>
				</view>
			</view>
			<view style="height: 40rpx;background-color: #f5f7fa;"></view>
			<view class="form">
				<view class="form-item">
					<view class="label required">是否搭设安全设施</view>
					<view class="form-content">
						<u-switch v-model="fillForm.isSafetyMeasure" />
						<text>{{fillForm.isSafetyMeasure ? "有" : "无"}}</text>
					</view>
				</view>
				
				<view class="form-item">
					<view class="label required">施工结束时间</view>
					<view @click="buildEndDatePicker = true" class="form-content">
						<view class="form-text" style="max-width: 336upx;">{{fillForm.buildEndDate}}</view>
						<u-icon name="arrow-right" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>
				<u-datetime-picker @confirm="confirmBuildEndDate" @cancel="buildEndDatePicker = false" :show="buildEndDatePicker" :minDate="(new Date()).getTime()" :formatter="dateFormatter" mode="datetime" />
			</view>

			<view class="footer-button">
				<view class="button-placeholder"></view>
				<view class="button-group">
					<button @click="clickSubmit" :loading="isLoading" class="button-primary">提交</button>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
 	import { mapGetters } from "vuex";
	import { getSystemHeightInfo, isPositiveInteger, imgFun, getFormCheckResult } from "@/utils/common.js";
	import { handleFormatDate, compareDate } from "@/utils/date.js";
	import fileMixin from "@/mixins/file.js";
	import { saveFilleport } from "@/api/engineeringMaintenance/engineeringMaintenance.js";
	import { getPermission } from "@/utils/common.js"
	import permision from "@/js_sdk/wa-permission/permission.js"
import { rejects } from "assert";
	export default {
		name: "fill-report",
		mixins: [fileMixin],
		props: {
			// 当前页面的类型 - 0: 综合大修下的  1: 工程维保下的
			type: {
				type: Number,
				default: 0,
			}
		},
		data() {
			return {
				// 容器之外的高度
				containerOutsideHeight: 0,
				// 填报表单
				fillForm: {
					project: null,
					intervalSite: [],
					supervisor: [],
					sideStationFiles: [],
					laborServiceNum: null,
					signFiles: [],
					spotFiles: [],
					workPersonnel: [],
					isWorkAllow: false,
					workAllowList: [],
					isSafetyMeasure: false,
					buildEndDate: '',
					
					sideStationDocId: 0,
					signFilesDocId: 0,
					spotFilesDocId: 0,
					
				},
				// 施工结束时间日期弹框显示状态
				buildEndDatePicker: false,
				// 是否在加载中
				isLoading: false,
				location:undefined,
			}
		},
		computed: {
			...mapGetters(['dictMap'])
		},
		watch: {
			// 'fillForm.loaction':{
			// 	handler(newVal, oldVal) {
			// 		console.log(newVal, oldVal, '监听')
			// 		if(!newVal || !oldVal) {
			// 			this.getCurrentPosition()
			// 		}
			// 	},
			// 	deep:true
			// }
		},
		async created() {

			this.initContainerData();
			// #ifdef APP
			this.checkOpenGPSServiceByAndroid()
			// #endif
			// #ifdef MP-WEIXIN
			console.log(121)
			await this.getCurrentPosition()
			// #endif
		},
		methods: {
			async getCurrentPosition() {
				console.log('方法内');
				return await new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success:async (res) => {
							console.log(res, 'api返回')
							if(!res.latitude || !res.longitude) {
								uni.showToast({
									title:'无法获取您的位置信息,请检查是否已打开定位服务',
									icon:'none',
									mask:true
								})
								setTimeout(() => {
									uni.switchTab({
										url: `/pages/homePage/homePage`
									})
									return
								},2000)
							}
							this.location = this.gcj02tobd09(res.latitude, res.longitude)
							resolve(true)
						},
						fail: (err) => {
							console.log(err);
							uni.showToast({
								title:'无法获取您的位置信息,请检查是否已打开定位服务',
								icon:'none',
								mask:true
							})
							setTimeout(() => {
								uni.switchTab({
									url: `/pages/homePage/homePage`
								})
								resolve(false)
								return
							},2000)
							
						},

					});
				})

			},
			/**检查是否打开GPS功能（android）**/
			checkOpenGPSServiceByAndroid() {			
			  let system = uni.getSystemInfoSync();// 获取系统信息
			
			  if (system.platform === 'android') { // 判断平台
			
			    var context = plus.android.importClass("android.content.Context");
			
			    var locationManager = plus.android.importClass("android.location.LocationManager");
			
			    var main = plus.android.runtimeMainActivity();
			
			    var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			
			    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			
			      uni.showModal({
			
			        title: '提示',
			
			        content: '请打开定位服务功能',
			
			        showCancel: false, // 不显示取消按钮
			
			        success() {
			
			          if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			
			            var Intent = plus.android.importClass('android.content.Intent');
			
			            var Settings = plus.android.importClass('android.provider.Settings');
			
			            var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
			
			            main.startActivity(intent); // 打开系统设置GPS服务页面
			
			          } else {
			
			            console.log('GPS功能已开启');
			
			          }
			
			        }
			
			      });
			
			    }
			
			  } 
			
			},
			
			gcj02tobd09(lng, lat) {
			   var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
			   var lat = +lat;
			   var lng = +lng;
			   var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
			   var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
			   var bd_lng = z * Math.cos(theta) + 0.0065;
			   var bd_lat = z * Math.sin(theta) + 0.006;
			   return bd_lng + ',' + bd_lat
			 },
			/** 初始化容器数据 */
			initContainerData() {
				const { stateHeight, bottomHeight, navbarHeight } = getSystemHeightInfo();
				
				this.containerOutsideHeight = stateHeight + bottomHeight + navbarHeight + 70;
			},
			
			/** 其他页面选择完后回显数据 */
			showDataByOtherPage() {
				if(uni.getStorageSync("_temp_select_project")) {
					this.fillForm.project = uni.getStorageSync("_temp_select_project");
					uni.removeStorageSync("_temp_select_project");
					this.fillForm.intervalSite = [];
					this.fillForm.supervisor = [];
					this.fillForm.workPersonnel = [];
				}
				if(uni.getStorageSync("_temp_select_interval_or_site")) {
					this.fillForm.intervalSite = uni.getStorageSync("_temp_select_interval_or_site");
					uni.removeStorageSync("_temp_select_interval_or_site");
				}
				if(uni.getStorageSync("_temp_select_supervisor")) {
					this.fillForm.supervisor = uni.getStorageSync("_temp_select_supervisor");
					uni.removeStorageSync("_temp_select_supervisor");
				}
				if(uni.getStorageSync("_temp_select_special_work_personnel") || uni.getStorageSync("_temp_select_special_work_personnel") === null) {
					this.fillForm.workPersonnel = uni.getStorageSync("_temp_select_special_work_personnel");
					uni.removeStorageSync("_temp_select_special_work_personnel");
				}
			},
			
			/**
			 * 跳转页面
			 * 1: 点击选择项目名称  2: 点击选择区间站点  3: 点击选择安全监管人员  4: 点击选择特殊工种作业人员
			 * */
			jumpPageByType(type) {
				if(type === 1) {
					uni.navigateTo({ url: `/subpackage-disclose/pages/select/select-project?type=${this.type}` });
				}
				else if(type === 2) {
					if(!this.fillForm.project) {
						uni.showToast({ title: "请选择项目", icon: "none" });
						return;
					}
					if(this.type === 1 && this.fillForm.intervalSite) {
						uni.setStorageSync("_temp_select_interval_or_site", this.fillForm.intervalSite);
					}
					uni.navigateTo({ url: `/subpackage-disclose/pages/select/select-interval-or-site?type=${this.type}&projectId=${this.fillForm.project.id}` });
				}
				else if(type === 3) {
					if(!this.fillForm.project) {
						uni.showToast({ title: "请选择项目", icon: "none" });
						return;
					}
					if(this.fillForm.supervisor) {
						uni.setStorageSync("_temp_select_supervisor", this.fillForm.supervisor);
					}
					uni.navigateTo({ url: `/subpackage-disclose/pages/select/select-supervisor?type=${this.type}&projectId=${this.type === 1 ? this.fillForm.project.projectOrgId : this.fillForm.project.orgId}` });
				}
				else if(type === 4) {
					if(!this.fillForm.project) {
						uni.showToast({ title: "请选择项目", icon: "none" });
						return;
					}
					if(this.fillForm.workPersonnel) {
						uni.setStorageSync("_temp_select_special_work_personnel", this.fillForm.workPersonnel);
					}
					uni.navigateTo({ url: `/subpackage-disclose/pages/select/select-special-work-personnel?type=${this.type}&projectId=${this.type === 1 ? this.fillForm.project.projectOrgId : this.fillForm.project.orgId}` });
				}
			},
			
			/** 添加文件 */
			async addFile(event, key, index) {
				if(index !== undefined) {
					if(key === "workAllowList") {
						for(const item of event.file) {
							this.fillForm[key][index].fileArray.push({...item, url: await imgFun(item)});
						}
					}
				}
				else {
					for(const item of event.file) {
						this.fillForm[key].push({...item, url: await imgFun(item)});
					}
				}
			},
			
			/** 删除文件 */
			deleteFile(event, ...params) {
				const [key1, key2, index] = params;
				
				if(index !== undefined) {
					this.fillForm[key1][index][key2].splice(event.index, 1);
				}
				else {
					this.fillForm[key1].splice(event.index, 1);
				}
			},
			// 选择有即添加一个作业许可
			addOneDataWorkAllow(value){
				if(value){
					this.addWorkAllowList()
				}else{
					this.fillForm.workAllowList = []
				}
			},
			/** 添加作业许可 */
			addWorkAllowList() {
				this.fillForm.workAllowList.push({index: null, fileArray: [], docId: 0});
			},
			
			/** 选择作业许可 */
			selectWorkAllowName(event, index) {
				// 判断是否重复...
				if(this.fillForm.workAllowList.find(item => item.index === event.detail.value)) {
					uni.showToast({ title: "当前作业许可证已经存在", icon: "none" });
					return;
				}
				
				this.$set(this.fillForm.workAllowList, index, {...this.fillForm.workAllowList[index], index: event.detail.value});
			},
		
			/** 删除作业许可 */
			removeWorkAllowList(index) {
				this.fillForm.workAllowList.splice(index, 1);
				if(!this.fillForm.workAllowList.length) {
					this.fillForm.isWorkAllow = false;
				}
			},
		
			/** 确认选择施工结束日期 */
			confirmBuildEndDate(event) {
				this.fillForm.buildEndDate = handleFormatDate(event.value, 3);
				this.buildEndDatePicker = false;
			},
		
			/** 上传文件 */
			async uploadFiles() {
				const { sideStationFiles, signFiles, spotFiles, workAllowList } = this.fillForm;

				const docIdArray = await Promise.all([
					this.uploadFileList(sideStationFiles),
					this.uploadFileList(signFiles),
					this.uploadFileList(spotFiles)
				]);
				this.fillForm.sideStationDocId = docIdArray[0];
				this.fillForm.signFilesDocId = docIdArray[1];
				this.fillForm.spotFilesDocId = docIdArray[2];
				for(const index in workAllowList) {
					const docId = await this.uploadFileList(workAllowList[index].fileArray);
					this.fillForm.workAllowList[index].docId = docId;
				}
			},
			
			/** 保存每日交底填报的内容 */
			handleSaveFilleport() {
				return new Promise(resolve => {
					const {
						project, intervalSite, supervisor, sideStationFiles, laborServiceNum, signFiles, spotFiles,
						workPersonnel, isWorkAllow, workAllowList, isSafetyMeasure, buildEndDate, sideStationDocId,
						signFilesDocId, spotFilesDocId, workAllowDocId
					} = this.fillForm;
					console.log(this.location,'位置');
					saveFilleport({
						location:this.location,
						projectId: uni.getStorageSync("isOwner"),
						type: this.type === 1 ? "gcwb" : "zhdx",
						bpId: project.id,
						pbName: project.name,
						lineSiteSectionVoList: intervalSite.map(item => ({
							lineId: item.lineId,
							lineName: item.lineName,
							lineSiteSectionId: item.lineSiteSectionId,
							lineSiteSectionName: item.lineSiteSectionName,
							lineSiteSectionType: item.lineSiteSectionType,
						})),
						personnelCallVoList: supervisor.map(item => ({
							relationType: "aqjg",
							personId: item.id,
							personName: item.name,
						})),
						sidePhotoDoc: sideStationDocId,
						labourServicePerson: parseInt(laborServiceNum),
						signatureFileDoc: signFilesDocId,
						localeDoc: spotFilesDocId,
						personnelCallVoList1: workPersonnel.map(item => ({
							relationType: "tsgz",
							personId: item.id,
							personName: item.name,
						})),
						workPermit: isWorkAllow ? "y" : "n",
						workPermitVoList: workAllowList.map(item => ({
							workPermitName: this.dictMap['work_permit_name'][item.index].code,
							docId: item.docId,
						})),
						safetyPractice: isSafetyMeasure ? "y" : "n",
						endConstructionDate: handleFormatDate(buildEndDate, 3),
						
					}).then(res => {
						uni.showToast({ title: res.message, icon: "none" });
						this.initFillForm();
						resolve();
					});
				});
			},
		
			/** 点击提交按钮 */
			async clickSubmit() {
				console.log(this.fillForm,'=====')
				// 表单校验...
				if(!getFormCheckResult(this.fillForm, ['sideStationDocId', 'signFilesDocId', 'spotFilesDocId', 'workPersonnel', 'workAllowList'])) {
					uni.showToast({ title: "请检查表单是否填写完整", icon: "none" });
					return;
				}
				else if(!isPositiveInteger(this.fillForm.laborServiceNum)) {
					uni.showToast({ title: "劳务人员必须大于等于0的整数", icon: "none" });
					return;
				}
				else if(this.fillForm.isWorkAllow) {
					if(!this.fillForm.workAllowList.length) {
						uni.showToast({ title: "最少添加一个作业许可", icon: "none" });
						return;
					}
					else {
						for(const item of this.fillForm.workAllowList) {
							if(!getFormCheckResult({...item, index: item.index !== null ? item.index.toString() : null}, ["docId"])) {
								uni.showToast({ title: "请将作业许可填写完整", icon: "none" });
								return;
							}
						}
					}
				}
				if(!compareDate(this.fillForm.buildEndDate, new Date())) {
					uni.showToast({ title: "施工结束时间不可早于提交时间！", icon: "none" });
					return;
				}
				// #ifdef APP-PLUS
					await this.getCurrentPosition()
					let str = await getPermission('android.permission.ACCESS_FINE_LOCATION')
					console.log(str, '去那先')
					if(str !== '已获得授权') {
						uni.showModal({
							title: '提示',
							content: '请先允许获取位置定位权限',
							success: res => {
								if (res.confirm) {
									permision.gotoAppPermissionSetting()
								} else if (res.cancel) {
									uni.switchTab({
										url: `/pages/homePage/homePage`
									})
								}
							}
						});
					}

				// #endif
				if(!this.location || this.location === '0.0065,0.006') {
					uni.showModal({
						title:'提示',
						showCancel: false, // 不显示取消按钮
						content: '位置信息获取失败!请检查是否打开Gps服务或是否允许获取当前位置',
						success: (res) => {
							setTimeout(() => {
								uni.switchTab({
									url: `/pages/homePage/homePage`
								})
								return
							},1200)
						}
					})
					return
				}
				// 调用接口...
				if(!this.isLoading) {
					this.isLoading = true;
					await this.uploadFiles();
					await this.handleSaveFilleport();
					this.$emit("refreshFillRecordNotUploadCount");
					this.isLoading = false;
				}
			},
			
			/** 初始化表单 */
			initFillForm() {
				this.fillForm = {
					project: null,
					intervalSite: [],
					supervisor: [],
					sideStationFiles: [],
					laborServiceNum: null,
					signFiles: [],
					spotFiles: [],
					workPersonnel: [],
					isWorkAllow: false,
					workAllowList: [],
					isSafetyMeasure: false,
					buildEndDate: '',
					
					sideStationDocId: 0,
					signFilesDocId: 0,
					spotFilesDocId: 0,
				};
			},
			
			/** 日期选择格式化 */
			dateFormatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				else if (type === 'month') {
					return `${value}月`
				}
				else if (type === 'day') {
					return `${value}日`
				}
				else if (type === 'hour') {
					return `${value}时`
				}
				else if (type === 'minute') {
					return `${value}分`
				}
				return value;
			},
		}
	}
</script>

<style scoped lang="scss">
	.fill-report {
		.form {
			background: #fff;
			padding-top: 26upx;
			
			.form-item {
				height: 100upx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin: 0 30upx;
				border-bottom: 1px solid #e2e5ed;
				
				&:last-of-type {
					border-bottom: none;
				}
				
				.label {
					color: #445469;
					line-height: 44upx;
					flex-shrink: 0;
				}
				
				.form-content {
					color: #22204e;
					display: flex;
					align-items: center;
				}
				
				.form-text {
					line-height: 58upx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					max-width: 302upx;
				}
				.form-text.none {
					opacity: .7;
					font-size: 30rpx;
				}
				
				.u-icon {
					margin-left: 40upx;
				}
				
				.uicon-close-circle-fill {
					margin-left: 32upx;
				}
				
				.u-input {
					width: 340upx;
					text-align: right;
					
					::v-deep .u-input__content__field-wrapper {
						margin-right: 24upx;
					}
					
					::v-deep .uni-input-wrapper {
						text-align: right;
					}
				}
				
				.u-switch {
					margin-right: 30upx;
				}
			}
			
			.no-inline {
				display: block;
				height: auto;
				
				.label {
					line-height: 100upx;
				}
			}
		}
	}
	
	.footer-button {
		height: 154upx;
		
		.button-placeholder {
			height: 100%;
		}
		
		.button-group {
			height: 154upx; 
			padding: 30upx; 
			box-sizing: border-box; 
			background: #fff; 
			position: fixed; 
			width: 100vw; 
			bottom: 0; 
			z-index: 1;
			
			.button-primary {
				background: #2f80ed; 
				border-radius: 4upx; 
				color: #fff; 
				font-weight: bold; 
				line-height: 92upx; 
				text-align: center;
			}
		}
	}
	
	.required {
		&::before {
			content: "*";
			color: #ff6a6a;
		}
	}
</style>
